<template>
  <a-modal
    class="relative"
    width="90%"
    :visible="visible"
    :title="title"
    :footer="null"
    :mask-closable="false"
    @cancel="onCancel"
  >
    <div class="m-b-5">当前选中地点：{{ modalData.location }}</div>
    <div id="container" />
    <a-input-search
      id="searchInput"
      v-model:value="searchValue"
      style="width: 300px"
      class="absolute top-140px right-45px"
      placeholder="查找地点"
      allow-clear
      @search="onSearch"
    >
      <template #enterButton>
        <a-button size="small" type="primary">搜索</a-button>
      </template>
    </a-input-search>
    <a-space class="w-full justify-center m-t-5">
      <a-button type="primary" @click="onOk">确认</a-button>
      <a-button @click="onCancel">关闭窗口</a-button>
    </a-space>
  </a-modal>
</template>

<script setup lang="tsx">
  import AMapLoader from '@amap/amap-jsapi-loader';

  defineOptions({
    name: 'SelectLocationModal',
  });
  const props = defineProps({
    visible: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: '选择地点',
    },
    selectedLocation: {
      type: String,
      default: '',
    },
    center: {
      type: Array,
      default: () => [],
    },
  });
  const emit = defineEmits(['ok', 'cancel']);
  const { visible, selectedLocation, center } = toRefs(props);
  const searchValue = ref<string>();
  let modalData = reactive<any>({
    lng: null,
    lat: null,
    location: '',
  });
  watchEffect(() => {
    if (visible.value) {
      !map && initMap();
      modalData.lng = center.value[0] || 116.681212;
      modalData.lat = center.value[1] || 39.852698;
      modalData.location = selectedLocation.value;
      console.info('modalDat==>', map);
    }
  });

  let map: {
    on: (
      arg0: string,
      arg1: (event: { lnglat: { getLng: Function; getLat: Function } }) => void,
    ) => void;
    setCenter: (arg0: any) => void;
    add: (arg0: { setPosition: (arg0: { getLng: Function; getLat: Function }) => void }) => void;
    setFitView: () => void;
    destroy: () => any;
  };
  let geoCoder: {
      getAddress: (arg0: any[], arg1: (status: string, result: { info: string }) => void) => void;
    },
    placeSearch: { search: (arg0: string) => void; setCity: (arg0: number) => void },
    autoComplete: {
      on: (arg0: string, arg1: (event: { poi: { name: string; adcode: number } }) => void) => void;
    },
    geolocation: { getCurrentPosition: (arg0: PositionCallback) => void },
    marker: { setPosition: (arg0: { getLng: Function; getLat: Function }) => void };

  const pluginsList = [
    'AMap.AutoComplete',
    'AMap.PlaceSearch',
    'AMap.Geolocation',
    'AMap.Geocoder',
  ];

  const onSearch = (value: string) => {
    if (!value) return;
    placeSearch.search(value);
    console.info(marker);
  };
  const onOk = () => {
    emit('ok', modalData);
    onCancel();
  };
  const onCancel = () => {
    emit('cancel');
    modalData = {};
  };
  const updateModalData = (lnglat: { lng: number; lat: number }) => {
    geoCoder.getAddress(
      [lnglat.lng, lnglat.lat],
      (status: string, result: { info: string; regeocode: { formattedAddress: string } }) => {
        if (status === 'complete' && result.info === 'OK') {
          console.info('result ==>', result);
          modalData.lng = lnglat.lng;
          modalData.lat = lnglat.lat;
          modalData.location = result.regeocode.formattedAddress;
        }
      },
    );
  };
  const clickHandler = (event: {
    lnglat: { getLng: Function; getLat: Function; lng: number; lat: number };
  }) => {
    console.info('event ==>', event);
    marker.setPosition(event.lnglat);
    updateModalData(event.lnglat);
  };
  const initMap = async () => {
    const isHasCenter = center.value && center.value.length > 1;
    const { Map, LngLat, Marker, plugin, PlaceSearch, AutoComplete, Geolocation, Geocoder } =
      await AMapLoader.load({
        // 使用高德地图，填写key值
        key: '976db7ad27375e5',
        version: '2.0',
        plugins: pluginsList,
      });
    const mapOptions = {
      viewMode: '2D', // 是否为3D地图模式
      zoom: 11, // 初始化地图级别
      doubleClickZoom: false, // 是否允许鼠标双击放大地图,
    };
    map = new Map('container', mapOptions);
    const drawMarker = (position: { lng: number; lat: number }) => {
      const pos = new LngLat(position.lng, position.lat);
      map.setCenter(pos);
      marker = new Marker({
        position: pos,
        title: '当前位置',
      });
      map.add(marker);
      map.setFitView();
    };
    map.on('click', clickHandler);
    if (isHasCenter) drawMarker({ lng: modalData.lng, lat: modalData.lat });

    plugin(pluginsList, () => {
      const autoOptions = {
        city: '全国',
        input: 'searchInput',
      };
      autoComplete = new AutoComplete(autoOptions);
      placeSearch = new PlaceSearch({ map });
      autoComplete.on('select', (event: { poi: { name: string; adcode: number } }) => {
        placeSearch.setCity(event.poi.adcode);
        console.info('select ==>', event);
      });
      geoCoder = new Geocoder({
        radius: 1000,
        extensions: 'all',
      });
      geolocation = new Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位，默认：true
        timeout: 10000, // 设置定位超时时间，默认：无穷大
        offset: [10, 20], // 定位按钮的停靠位置的偏移量
        zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        position: 'RB', //  定位按钮的排放位置,  RB表示右下
      });
      if (isHasCenter) return;
      geolocation.getCurrentPosition(((status: string, result: any) => {
        if (status === 'complete') drawMarker(result.position);
      }) as unknown as PositionCallback);
    });
  };
  onUnmounted(() => {
    map && map.destroy();
  });
</script>

<style scoped lang="less">
  #container {
    width: 100%;
    height: 450px;
  }
</style>
